package com.filter;

import com.MybatisUtil.MybatisUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.regex.Pattern;

//@WebFilter(urlPatterns = "/*",filterName = "SqlSessionFilter")
public class SqlSessionFilter implements Filter {

   // Logger log = Logger.getLogger(SqlSessionFilter.class);
    static String reg =
            "(/\\w+)*/\\w+\\.(jpg|png|gif|bmp|css|html|ico|htm|jsp|mp4|mp3|avi|mkv|rmvb|rm)";
    // 请求->b(servlet)->c(dao)
    // 响应<-
    // a(过滤器)->b->c
    // a最先开始，最后完成
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        HttpServletRequest hReq = (HttpServletRequest) servletRequest;
        // http://localhost:8080/a/b/xxx?sdfsffds
        // path = /a/b/xxx
        String path = hReq.getServletPath();
        // trace/debug/info/warn/error/fetal error
        //log.debug(hReq.getRemoteAddr()+" request ["+path+"] start...");
        boolean match = Pattern.matches(reg, path);
        if(path!=null && !match){
            try {
                // 1、请求
                //log.debug(hReq.getRemoteAddr()+" request ["+path+"] open SqlSession...");
                MybatisUtil.open();
                // 2、目标（Servlet、Jsp、静态资源），b
                //log.debug(hReq.getRemoteAddr()+" request ["+path+"] start execute sql...");
                filterChain.doFilter(servletRequest, servletResponse);
                //log.debug(hReq.getRemoteAddr()+" request ["+path+"] end execute sql...");
            }catch (Exception e){
                MybatisUtil.rollback();
                //log.debug(hReq.getRemoteAddr()+" request ["+path+"] execute sql exception:"+e.getMessage());
                throw e;                  // 为啥要抛出异常？
            }finally {
                //log.debug(hReq.getRemoteAddr()+" request ["+path+"] close SqlSession...");
                // 3、响应
                MybatisUtil.close();
            }
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
        //log.debug(hReq.getRemoteAddr()+" request ["+path+"] end!!!");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void destroy() {
    }
}
